package com.sy.jtamqproducer.service;

import java.util.Optional;
import java.util.UUID;

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.sy.jtamqproducer.dao.TestS2Reposity;
import com.sy.jtamqproducer.dao.TraLogReposity;
import com.sy.jtamqproducer.pojo.TestS2;
import com.sy.jtamqproducer.pojo.TraLog;

@Service
public class TestService {
	
	@Autowired
	private TestS2Reposity testS2Reposity;
    @Autowired
	private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private TraLogReposity traLogReposity;
    
    private static final String TOPIC ="test";

	public TestS2 getTest(int i) {
		Optional<TestS2> testS2 = testS2Reposity.findById(i);
		return testS2.orElse(null);
	}
	
	
	public void saveTest(TestS2 testS2) {
		String transactionId = UUID.randomUUID().toString();
		String s2Json = JSONObject.toJSONString(testS2);
		
        rocketMQTemplate.sendMessageInTransaction(TOPIC,
                 MessageBuilder.withPayload(s2Json)//用于客户端消费
                .setHeader(RocketMQHeaders.TRANSACTION_ID, transactionId)
                .setHeader("body", s2Json)
                .build(), testS2);
	}

	
	@Transactional
	public void saveJtaTest(TestS2 testS2, String transactionId) {
		//1.保存testS2
		testS2Reposity.save(testS2);
		//2.当本地事务成功，保存事务日志
		TraLog traLog = new TraLog();
		traLog.setId(transactionId);
		traLogReposity.save(traLog);
	}

}
